package com.itheima.tlias84.exception;

import com.itheima.tlias84.utils.ResultUtil;
import org.apache.http.MethodNotSupportedException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

/**
 * 因为我们无法使用try catch 捕获进入controller层 之前的异常，但是可以使用AOP对 controller调用之前 的增强
 * 因此这个注解相当于环绕通知 ，@RestControllerAdvice可以捕获controller层抛出的异常
 * 之前 400 之后 500
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)  //异常的错误  算术异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 返回响应码500
    public ResultUtil handleArithmeException(ArithmeticException e) {
        return ResultUtil.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class) //捕获异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultUtil handleMethodNotSupportedException(MethodArgumentNotValidException e) {
        String defaultMessage = e.getFieldError().getDefaultMessage(); //手机号格式错误
        Object rejectedValue = e.getFieldError().getRejectedValue(); //用户输入的数据

        //获取全部的校验信息
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringJoiner stringJoiner = new StringJoiner(",","[","]");
        for(FieldError fieldError : fieldErrors){
            stringJoiner.add(fieldError.getDefaultMessage());
        }
        return ResultUtil.fail(stringJoiner.toString());
    }
}
